import { Component } from 'react';

import {TabBar, Toast, Group, Boxs, Badge, Grid, ScrollList, Slide} from 'saltui';
const {HBox, Box } = Boxs;
import AngleRight from 'salt-icon/lib/AngleRight';

import DB from '../../../app/db';
import { URLS,nodataIcon } from '../../../app/variables';

import './PageHome.less';

Date.prototype.format = function (fmt) { 
  var o = {    
    "M+": this.getMonth() + 1, //月份     
    "d+": this.getDate(), //日     
    "H+": this.getHours(), //小时     
    "m+": this.getMinutes(), //分     
    "s+": this.getSeconds(), //秒     
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度     
    "S": this.getMilliseconds() //毫秒     
  };    
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));    
  for (var k in o)    
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));    
  return fmt;    
}

let currentItem = { activeItem: "0"};

const Item1  =  React.createClass({

detailsClick: function(event) {
    var url ='meeting/meetingDetails/'+this.props.applyRecordid + '/notice';
    location.hash = url;
},
render:function() {
  return <div> 
    <Group.List lineIndent={60}>
      <div className="dd-t-list-wrap" onClick={this.detailsClick}>
        <HBox vAlign="center">
          <HBox flex={1}  className="t-FBAC">
            <Box  className="dd-t-list-img t-ML10">
                <div className="t-LH1_4" style={{fontSize:10}}>{this.props.day}</div>
                <div className="t-FS10 t-LH1_4" style={{fontSize:10}}>{this.props.week}</div>
            </Box>
            <Box className="dd-t-list-text-content" flex={1}>
              <div className="t-list-title t-omit t-LH1_4 ">
                <span>{this.props.applyRecordName}</span>
                <span className={this.props.status==0?'t-badge-o t-FR':'t-DN'}>NEW</span>
              </div>
              <div className="dd-t-list-time t-FBAC">
                <div className="t-FBAC"> 
                <i className="iconfont icon-time t-FCc t-MR4" style={{fontSize:14}}></i><span className="t-list-text t-MR12">{this.props.startTime}~{this.props.endTime}</span>
                <i className="iconfont icon-place t-FCc t-MR4" style={{fontSize:14}}></i>
                <span className="t-list-text t-MR4">{this.props.boardroomName}</span></div>
              </div>
              </Box>
            </HBox>
            <Box>
              <AngleRight width={20} fill="#ccc" className="demo-t-list-arrow" />
            </Box>
          </HBox>
        </div>
      </Group.List>
    </div>
  }
});
     

export default class PageHome extends Component {

 constructor(props) {
    super(props);

    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var homeHeight = '';
    var taskListHeight = '';
    if(isAndroid==true){
        homeHeight = window.screen.height-187-36-52+"px";
    }else if(isiOS==true){
        homeHeight = window.screen.availHeight-187-36-52+"px";
    }else {
        if(window.screen.availHeight) {
            homeHeight = '550px';
        }
    }
    // debugger;
    // alert("0===="+storage.get('isRefresh'));
    // alert(DB);
    // storage.set("isRefresh","1");
    // alert("1===="+storage.get('isRefresh'));
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isMask = false;
    var isWelcome = false;
    var isHelpNew = false;
    var isLogin = "";
    var welcome = "";
    var helpNew = "";
    dd.util.domainStorage.getItem({ //欢迎页
       name:'meeting_welcome_'+userId , // 存储信息的key值
       onSuccess : function(info) {
           welcome = info.value;
           if( typeof(welcome) == 'undefined' || welcome == '' ){
               isWelcome = true;
           }
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });

    if(!isWelcome){
      dd.util.domainStorage.getItem({ //帮助按钮
         name:'meeting_helpNew_'+userId , // 存储信息的key值
         onSuccess : function(info) {
              helpNew = info.value;
              if( typeof(helpNew) == 'undefined' || helpNew == '' ){
                isHelpNew = true;
              }
              //初始化按钮
              t.initButton(isHelpNew);
         },
         onFail : function(err) {
              //alert(JSON.stringify(err));
         }
      });
    }

    dd.util.domainStorage.getItem({ //帮助首页
      name:'meeting_'+userId , // 存储信息的key值
      onSuccess : function(info) {
         //alert(JSON.stringify(info));
         isLogin = info.value;
         if( typeof(isLogin) == 'undefined' || isLogin == '' ){
             isMask = true;
         }
      },
      onFail : function(err) {
          //alert(JSON.stringify(err));
      }
    });
    
    this.state = {
      userId:userId,
      isMask:isMask,
      isWelcome:isWelcome,
      isHelpNew:isHelpNew,
      approveNum:'0',
      memoCount:'0',
      homeHeight: homeHeight
    };

    this.tabBarItems = [
      {title: '首页',icon: <span className="iconfont icon-tab-home"></span>,path: '/star'},
      {title: '会议室',icon:<span className="iconfont icon-tab-meeting"></span>,path: '/a/star'},
      {title: '',icon: <i className="iconfont icon-add t-FCf"></i>,iconHeight: 40,path: '/center',items: []},
      { title: '我的会议', icon: <span className="iconfont icon-mine"></span>,path: '/b/star'},
      { title: '任务', icon: <span className="iconfont icon-task"></span>,path: '/b/star'}
    ]; 
  }

  componentDidMount(){
    var page_title = "首页";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : page_title,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: page_title,
            icon: '',
            actionmenu: {}
        },
      });
    }
  }

  // 请求参数
  beforeFetch(data,from){
    return data;
  }

  // 首页返回数据参数
  processData(data){
    let approvalCount = data.approvalCount;
    this.setState({
      approveNum:approvalCount
    });
    let memoCount = data.memoCount;
    this.setState({
      memoCount:memoCount
    });
    return data;
  }

  // 进入会议纪要页面
  memo(){
    location.hash = 'meeting/memo';
  }

  // 进入会议审批页面
  approve(){
    location.hash = 'meeting/approve';
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*var iconIndex = 1;
    if(isHelpNew){
      iconIndex = 2;
    }
    dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : iconIndex,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

    /*跳到帮助*/
  skipHelp(path){
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
     name:'meeting_'+userId , // 存储信息的key值
     value:'isLogin', // 存储信息的Value值
     onSuccess : function(info) {
          //alert(JSON.stringify(info));
          t.setState({
              isMask:false
             });
          location.hash=path;
     },
     onFail : function(err) {
     }
    }); 
  }

  /*关闭提示*/
  closeTip(){
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
     name:'meeting_'+userId , // 存储信息的key值
     value:'isLogin', // 存储信息的Value值
     onSuccess : function(info) {
          //alert(JSON.stringify(info));
            t.setState({
              isMask:false
             });
     },
     onFail : function(err) {
          //alert(JSON.stringify(err));
     }
   });
  }

  //点击引导页按钮
  clickWelcome(){
    let t = this;
    var userId = this.state.userId;
    var isHelpNew = true;
    dd.util.domainStorage.setItem({
       name:'meeting_welcome_'+userId , // 存储信息的key值
       value:'isWelcome', // 存储信息的Value值
       onSuccess : function(info) {
              t.setState({
                isWelcome:false
               });
              t.initButton(isHelpNew);
       },
       onFail : function(err) {
       }
     });

  }

  handleClickHref(path){
    location.hash = path
  }

  scanQrcode(){
    let t = this;
    dd.biz.util.scan({
      type: "qrCode" , // type 为 all、qrCode、barCode，默认是all。
      onSuccess: function(data) {
        let t = this;
        let param = {id: data.text, signType: "0"};
        DB.SomeModuleAPI.userSigned(param).then((content) => {
          if(content.status == "1"){//不可以签到
            Toast.show({
              type: 'error',
              content: '未到签到时间',
              onHide: function () {
              }
            });
          }else if(content.status == "0"){//成功签到
            Toast.show({
              type: 'success',
              content: '签到成功'
            });
          }else if(content.status == "2"){//会议结束
            Toast.show({
              type: 'success',
              content: '会议已结束'
            });
          }else if(content.status == "3"){
            Toast.show({
              type: 'success',
              content: '会议已取消'
            });
          }else if(content.status == "-1"){
            Toast.show({
              type: 'text',
              content: '您没有参加该会议',
              onHide: function () {
              }
            });
          }
        }).catch((error) => {
          if(typeof(error.errorMsg) == 'undefined'){
            Toast.show({
            type: 'error',
            content: '提交出错'
             });
          }else{
            Toast.show({
            type: 'error',
            content: error.errorMsg
             });
          }
        });
      },
      onFail : function(err) {}
    })
  }

  changeActiveIndex(activeIndex){
    // 这里是触发每个item之后的回调，会返回当前点击的item的index 值
    if(activeIndex == 1){
      location.hash = 'meeting/boardRoomview';
    }else if(activeIndex == 2){
      location.hash = 'meeting/add';
    }else if(activeIndex == 3){
      location.hash = 'meeting/meetingList';
    }else if(activeIndex == 4){
      location.hash = 'meeting/taskMineList';
    }
  }

  render() {
    let t = this;
    let homeHeight = {height: this.state.homeHeight}

    return (
    <div className="page-meeting">
      <div className={this.state.isWelcome?'page-welcome':'t-DN'}>
         <Slide showNav loop={false}>
            <Slide.Item title="标题" className="t-image-slide-item" style={{background: "url(../../../fmui/images/meeting-welcome1.png) no-repeat center",backgroundSize: 'cover'}}>
            </Slide.Item>
            <Slide.Item className="t-image-slide-item" style={{background: "url(../../../fmui/images/meeting-welcome2.png) no-repeat center",backgroundSize: 'cover'}}>
            </Slide.Item>
            <Slide.Item className="t-image-slide-item" style={{background: "url(../../../fmui/images/meeting-welcome3.png) no-repeat center",backgroundSize: 'cover'}}>
            </Slide.Item>
            <Slide.Item className="t-image-slide-item" style={{background: "url(../../../fmui/images/meeting-welcome4.png) no-repeat center",backgroundSize: 'cover'}}>
              <span className="t-FC0" onClick={this.clickWelcome.bind(this)}></span>
            </Slide.Item>
         </Slide>
      </div>

      <div className={this.state.isWelcome?'t-DN':'info-home'}>
        <Grid col={3} square touchable>
            <div className="top-title" onClick={this.scanQrcode.bind(this)}>
              <div className="dd-top-icon">
                <i className="iconfont icon-scan t-FCyellow"></i>
              </div>
              <div className="menu-title">扫一扫</div>
            </div>
            <div className="top-title" onClick={this.approve.bind(this)}>
              <div className="dd-top-icon">
                <Badge count={t.state.approveNum}>
                  <a href="#1" className="demo-item" />
                </Badge>
                <i className="iconfont icon-approval t-FCgreen"></i>
              </div>
              <div className="menu-title">审批</div>
            </div>
            <div className="top-title" onClick={this.memo.bind(this)}>
              <div className="dd-top-icon">
                <Badge count={t.state.memoCount}>
                  <a href="#1" className="demo-item" />
                </Badge>
                <i className="iconfont icon-discribe t-FCblue"></i>
              </div>
              <div className="menu-title">会议纪要</div>
            </div>
          </Grid>

          <div className="t-grid-head t-grid-title">会议通知</div>
          <div style={} >
            <ScrollList
              className="page-list"
              url={URLS.attendNoticeInfoSetList}
              dataType="json"
              pageSize={10}
              beforeFetch={this.beforeFetch.bind(this)}
              processData={this.processData.bind(this)}
              ref = 'cms_infolist_ref'
              noDataImage={nodataIcon}
              currentPageKey="page">
              <Item1 type="0" />
            </ScrollList>
          </div>

          <TabBar activeIndex={0} onChange={this.changeActiveIndex.bind(this)} iconHeight={24} cIconHeight={50} items={this.tabBarItems} />

          <div className="tips-box" className={this.state.isMask?'tips-box':''}>
            <div className="tips-t-mask"></div>
            <div className="tips-modal-bg">
              <img src="../../../fmui/images/meeting-tips.png" alt="" style={{width: 330,height: 455}} />
              <div className="t-button-document" onClick={this.closeTip.bind(this)}>我知道了</div>
              <span onClick={this.skipHelp.bind(this,'help/help_index')}> 首次使用时，请管理员查看帮助完成参数设置 > </span>
            </div>
          </div>

        </div>
        <div onClick={this.handleClickHref.bind(this,'demo/aboutOne')} style={{bottom:'132', right:'17'}} className="t-animate" ><span className="dd-display">演示</span></div>
      </div>
    );
  }
}


